package jbl.service.impl;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jbl.dao.ThjDaoI;
import jbl.dao.TxgDaoI;
import jbl.io.excel.ExcelTool;
import jbl.io.excel.XgExcel;
import jbl.model.Thj;
import jbl.model.Tuser;
import jbl.model.Txg;
import jbl.pageModel.DataGrid;
import jbl.pageModel.Xg;
import jbl.service.XgServiceI;
import jbl.util.JblTool;
import jbl.util.Json;
import jbl.util.Message;

import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("xgService")
public class XgServiceImpl implements XgServiceI {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(XgServiceImpl.class);
	
	private TxgDaoI xgDao;
	
	private ThjDaoI hjdDao;
	
	@Autowired
	public void setHjdDao(ThjDaoI hjdDao) {
		this.hjdDao = hjdDao;
	}
	
	
	
	@Autowired
	public void setXgDao(TxgDaoI xgDao) {
		this.xgDao = xgDao;
	}

	@Override
	public DataGrid dataGrid(Xg xg) {
		// TODO Auto-generated method stub
		DataGrid dg = new DataGrid();
		try {
			List<Xg> xgList = new ArrayList<Xg>();
			Map<String, Object> params = new HashMap<String, Object>();
			String hql = " from Txg t where 1=1 ";
			hql = addWhere(hql , xg, params);
			String totalHql = "select count(*) " + hql;
			hql = addOrder(hql , xg);
			List<Txg> list = xgDao.find(hql, params, xg.getPage(), xg.getRows());
			if(null != list && list.size() > 0){
				for(Txg t : list){
					Xg xg1 = new Xg();
					BeanUtils.copyProperties(t, xg1);
					processFK(t, xg1);
					xgList.add(xg1);
				}
			}
			
			dg.setRows(xgList);
			dg.setTotal(xgDao.count(totalHql,params));
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error("查询xg信息error:"+e.getMessage());
		}
		return dg;
	}
	
	private String addOrder(String hql , Xg xg){
		if(null != xg.getSort()){
			if(xg.getSort().equals("hjList")){
				xg.setSort("thj.id");
			}
			if(xg.getSort().equals("userList")){
				xg.setSort("tuser.id");
			}
			hql += " order by t."+xg.getSort() +" " + xg.getOrder();
		}
		return hql;
	}
	
	private String addWhere(String hql , Xg xg , Map<String, Object> params){
		if(null != xg.getHjId()&&!"".equals(xg.getHjId())){
			hql += " and t.thj.id=:hjId ";
			params.put("hjId", xg.getHjId());
		}
		if(null != xg.getId()&&!"".equals(xg.getId())){
			hql += " and t.id LIKE "+"'%"+xg.getId()+"%' ";
		}
		if(null != xg.getAddUserId() && !"".equals(xg.getAddUserId())){
			hql += " and t.tuser.id=:userId ";
			params.put("userId", xg.getAddUserId());
		}
		if(null != xg.getEditUserId() && !"".equals(xg.getEditUserId())){
			hql += " and t.tuser1.id=:userId1 ";
			params.put("userId1", xg.getEditUserId());
		}
		return hql;
	}
	
	private void processFK(Txg t , Xg xg){
		Thj hj = t.getThj();
		if(null != hj){
			List<Object> list = new ArrayList<Object>();
			list.add(hj.getNumberID());
			list.add(hj.getId());
			list.add(hj.getName());
			list.add(hj.getFlag());
			xg.setHjList(list);
		}
		Tuser tuser = t.getTuser();
		if(null != tuser){
			xg.setAddUserId(tuser.getId());
			xg.setAddUserName(tuser.getName());
		}
		Tuser tuser1 = t.getTuser1();
		if(null != tuser1){
			xg.setEditUserName(tuser1.getName());
		}
	}

	@Override
	public Json delete(String ids) {
		Json j = new Json();
		try{
			if(null != ids){
				for(String id : ids.split(",")){
					if(!"".equals(id.trim())){
						Txg txg = xgDao.get(Txg.class, id);
						xgDao.delete(txg);
					}
				}
			}
			j.setMsg("删除成功");
			j.setSuccess(true);
		}catch(Exception e){
			e.printStackTrace();
			j.setMsg("删除失败");
		}
		return j;
	}

	@Override
	public Json edit(Xg xg) {
		// TODO Auto-generated method stub
		Json j = new Json();
		try {
			Txg txg = new Txg();
			BeanUtils.copyProperties(xg, txg);
			List<Object> list = xg.getHjList();
			if(null != list){
				Thj thj = new Thj();
				thj.setId(list.get(0).toString());
				txg.setThj(thj);
			}
			txg.setTuser1(JblTool.getTuser());
			if(null != xg.getAddUserId()){
				Tuser tuser = new Tuser();
				tuser.setId(xg.getAddUserId());
				txg.setTuser(tuser);
			}
			xgDao.update(txg);
			j.setMsg("更新成功");
			j.setSuccess(true);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error("更新失败:"+e.getMessage());
			j.setMsg("更新失败");
		}
		return j;
	}

	@Override
	public Json add(Xg xg) {
		Json j = new Json();
		try {
			Txg txg = xgDao.get(Txg.class, xg.getId());
			if(null != txg){
				j.setMsg("添加失败：改编号箱柜已存在！");
				return j;
			}else{
				txg = new Txg();
				BeanUtils.copyProperties(xg, txg);
				List<Object> list = xg.getHjList();
				if(null != list){
					Thj thj = new Thj();
					thj.setId(list.get(0).toString());
					txg.setThj(thj);
				}
				if(null == xg.getCjsj() || "".equals(xg.getCjsj())){
					txg.setCjsj(new Timestamp(new Date().getTime()));
				}
				txg.setTuser(JblTool.getTuser());
				xgDao.save(txg);
				j.setMsg("添加成功");
				j.setSuccess(true);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error("添加失败:"+e.getMessage());
			j.setMsg("添加失败");
		}
		return j;
	}



	@Override
	public Json upXgFile(Xg xg) {
		Json j = new Json();
		
		Workbook book = null; 
		try {
			List<FileItem> list = ExcelTool.getItemFile();
			for(FileItem item:list){
				if("xg_upload_excel".equals(item.getFieldName().trim())){
					xg.setFilename(item.getName());
					try {
						book = ExcelTool.createWorkBook(item.getInputStream(), xg.getFilename());//解析上传文件Excel
						 Sheet sheet =  book.getSheetAt(0);	
						 List<Txg> xgList = new ArrayList<Txg>();
				         for (int i = 1; i <= sheet.getLastRowNum(); i++) { //解析成功  输出
				             Row ros = sheet.getRow(i); 
				             String ros1 = String.valueOf(ros.getCell(1)).trim();	
				             String ros2 = String.valueOf(ros.getCell(2)).trim();
				            
				             String ros3 = String.valueOf(ros.getCell(3)).trim();
				             String ros4 = String.valueOf(ros.getCell(4)).trim();
				             String ros5 = String.valueOf(ros.getCell(5)).trim();
				             String ros6 = String.valueOf(ros.getCell(6)).trim();
				             String id = "";
				             Txg txg = new Txg();
				             if(!"null".equals(ros1) && !"".equals(ros1)){
				            	 try {
				            		 id = Message.doubleFormat.format(ros.getCell(1).getNumericCellValue());
								} catch (Exception e) {
									// TODO: handle exception
									e.printStackTrace();
									j.setMsg("箱柜编号(条码号)-"+ros1+"-格式不正确：第2列,第"+(i+1)+"行!");
				     				return j;
								}
				            	 
				            	 Txg txg1 = xgDao.get(Txg.class, id);
				     			if(null != txg1){
				     				j.setMsg("箱柜编号(条码号)-"+id+"-已存在：第2列,第"+(i+1)+"行!");
				     				return j;
				     			}
				            	 txg.setId(id);
				             }else{
				            	 j.setMsg("箱柜编号(条码号)不能为空：第2列,第"+(i+1)+"行!");
				            	 return j; 
				             }
				             
				             txg.setName(ExcelTool.toNyStr(ros2));

				             
				             if("null".equals(ros3) && "".equals(ros3)){
				            
				            	 j.setMsg("货架编号不能为空：第4列,第"+(i+1)+"行!");
				            	 return j; 
				             }else{
					             String hjHql = " from Thj t where t.numberID=:numberId ";
					             Map<String, Object> params = new HashMap<String, Object>();
					             params.put("numberId", ros3);
					             Thj hj = hjdDao.get(hjHql, params);
					             
					             if(null == hj){
					            	 j.setMsg("货架编号-"+ros3+"-数据库未记录：第4列,第"+(i+1)+"行!");
					            	 return j;
					             }else{
					            	 txg.setThj(hj);
					             }
				             }
	
				             if(!"null".equals(ros4) && !"".equals(ros4)){
				            	 if(ros5.equals(Message.KQ_ZT)){
				            		 txg.setFlag("T");
				            	 }else if(ros4.equals(Message.GB_ZT)){
				            		 txg.setFlag("F");
				            	 }else{
				            		 j.setMsg("状态信息-"+ros4+"-不正确：第5列,第"+(i+1)+"行!");
					            	 return j; 
				            	 }
				             }else{
				            	 txg.setFlag("T");
				             }
				            	 txg.setBz(ExcelTool.toNyStr(ros5));
				             if(!"null".equals(ros6) && !"".equals(ros6)){
				            	 try {
				            		 txg.setCjsj(Timestamp.valueOf(ros6));
								} catch (Exception e) {
									j.setMsg("创建日期-"+ros6+"-格式不正常：第7列,第"+(i+1)+"行!");
									return j;
								}
				             }else{
				            	 txg.setCjsj(Timestamp.valueOf(Message.timeFormat.format(new Date())));
				             }
				             xgList.add(txg);
				         } 
				         for(Txg t : xgList){
				        	 t.setTuser(JblTool.getTuser());
				        	 xgDao.save(t);
				         }
				         j.setMsg("导入成功");
				         j.setSuccess(true);
					} catch (FileNotFoundException e) {
						e.printStackTrace();
						j.setMsg("文件未找到!");
						return j;
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						j.setMsg("IO中断!");
						return j;
					}
				}
			}
			
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			j.setMsg("导入失败");
		}
		
		return j;
	}

	@Override
	public List<Xg> comboboxInfo() {
		List<Xg> xgList = new ArrayList<Xg>();
		try {
			
			String hql = " from Txg t ";
			List<Txg> list = xgDao.find(hql);
			if(null != list && list.size() > 0){
				for(Txg t : list){
					Xg xg1 = new Xg();
					BeanUtils.copyProperties(t, xg1);
					processFK(t, xg1);
					xgList.add(xg1);
				}
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error("查询货架信息error:"+e.getMessage());
		}
		return xgList;
	}

	@Override
	public List<XgExcel> getXgExcelList(Xg xg) {
		List<XgExcel> xgExcelList = new ArrayList<XgExcel>();
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			String hql = " from Txg t where 1=1 ";
			hql = addWhere(hql , xg, params);
			List<Txg> list = xgDao.find(hql, params);
			int xh = 1;
			if(null != list && list.size() > 0){
				for(Txg t : list){
					XgExcel xgExcel = new XgExcel();
					BeanUtils.copyProperties(t, xgExcel);
					processFK1(t, xgExcel);
					xgExcel.setNumXh(xh+"");
					xgExcel.setFlag(JblTool.toFlag(t.getFlag()));
					xgExcelList.add(xgExcel);
					xh++;
				}
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error("查询xg信息error:"+e.getMessage());
		}
		return xgExcelList;
	}
	
	private void processFK1(Txg t , XgExcel xg){
		Thj hj = t.getThj();
		if(null != hj){
			xg.setHjNumberId(hj.getNumberID());
			xg.setHjName(hj.getName());
			xg.setKfName(hj.getTkf().getName());
		}
	}
}
